package com.benio.ycfdisplayer.fresco.photoview;

import android.content.Context;
import android.content.res.TypedArray;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.benio.ycfdisplayer.R;
import com.benio.ycfdisplayer.displayer.DisplayListener;
import com.benio.ycfdisplayer.displayer.Options;
import com.benio.ycfdisplayer.displayer.YcfDisplayer;
import com.benio.ycfdisplayer.fresco.FrescoTarget;

/**
 * An {@link uk.co.senab.photoview.PhotoView} that uses like {@link com.benio.ycfdisplayer.fresco.FrescoDraweeView}
 * Created by zhangzhibin on 2016/9/29.
 */
public class FrescoPhotoView extends FrescoPhotoViewSupport {
    private FrescoTarget mTarget;

    public FrescoPhotoView(Context context) {
        super(context);
        init(context, null);
    }

    public FrescoPhotoView(Context context, AttributeSet attr) {
        super(context, attr);
        init(context, attr);
    }

    public FrescoPhotoView(Context context, AttributeSet attr, int defStyle) {
        super(context, attr, defStyle);
        init(context, attr);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        if (isInEditMode()) {
            return;
        }

        if (attrs != null) {
            TypedArray gdhAttrs = context.obtainStyledAttributes(attrs, R.styleable.SimpleDraweeView);
            if (gdhAttrs != null) {
                try {
                    if (gdhAttrs.hasValue(R.styleable.SimpleDraweeView_actualImageUri)) {
                        String uri = gdhAttrs.getString(R.styleable.SimpleDraweeView_actualImageUri);
                        setImageURI(uri);
                    }
                } finally {
                    gdhAttrs.recycle();
                }
            }
        }
    }

    /**
     * Displays an image given by the uri.
     *
     * @param uri uri of the image
     * @undeprecate
     */
    @Override
    public void setImageURI(Uri uri) {
        setImageURI(uri != null ? uri.toString() : "", null, null);
    }

    /**
     * Displays an image given by the uri string.
     *
     * @param uriString uri string of the image
     */
    public void setImageURI(@Nullable String uriString) {
        setImageURI(uriString, null, null);
    }

    public void setImageURI(String uriString, Options options) {
        setImageURI(uriString, options, null);
    }

    public void setImageURI(String uriString, Options options, DisplayListener listener) {
        if (mTarget == null) {
            mTarget = new PhotoViewTarget(this);
        }
        YcfDisplayer.get().display(uriString).listener(listener).options(options).into(mTarget);
    }
}
